<template>
    <div>
        <el-form :model="form" label-width="130px" :rules="rules" ref="form" class="pad-t-1">
            <el-form-item label="基本信息" class="one-label">
                <el-form-item label="排序：" label-width="170px" prop="sortNo">
                    <el-input v-model="form.sortNo" class="long-input"/>
                    <div class="tips">数字越大，排序越靠前，如果为空，默认排序方式为创建时间</div>
                </el-form-item>
                <el-form-item label="商品名称：" label-width="170px" prop="title">
                    <div class="flex long-input">
                        <el-input v-model="form.title" class="long-input-2" placeholder="请输入商品名称"/>
                        <el-input v-model="form.unit" class="short-input" placeholder="单位，如：个/件/包"/>
                    </div>
                </el-form-item>
                <el-form-item label="商品图片：" label-width="170px">
                    <div><span class="font-red">* </span>商品主图</div>
                    <div class="flex height-148">
                        <draggable id="content-box flex-item" v-model="form.goodsImages" dragable="true" :move="getdata" @update="datadragEnd">
                        <template v-for="(item, key) in form.goodsImages" >
                            <div class="pic-bar mar-r-30 flex-item"
                              :key="key" @mouseover.stop="itemOver(key)" @mouseout.stop="itemOut(-1)">
                                <div @click="deleteImgages(item,key)">
                                    <svg-icon icon-class="close"
                                      :class="{'active':key==curIndex || key==curHover}"
                                      class="close-icon font-16 noraml-hide" />
                                </div>
                                <img class="picture" :src="item.imageUrl"/>
                            </div>
                        </template>
                        </draggable>
                        <el-upload v-if="form.goodsImages.length<5"
                                   list-type="picture-card"
                                   action="/api/common/uploadFiles"
                                   accept="image/jpeg,image/gif,image/png,image/bmp"
                                   name="files" multiple
                                   :data="token"
                                   :show-file-list="false"
                                   v-loading="fileLoading"
                                   :on-success="handleUploadSuccess"
                                   :before-upload="beforeUpload">
                          <i class="el-icon-plus"></i>
                        </el-upload>
                    </div>
                    <div class="tips mar-t-3">建议尺寸：750*750像素，可以拖拽图片调整顺序，最多上传5张</div>
                </el-form-item>


                <el-form-item label="分享图片：" label-width="170px">
                  <div class="flex height-148">
                    <el-upload list-type="picture-card"
                               action="/api/common/uploadFiles"
                               accept="image/jpeg,image/gif,image/png,image/bmp"
                               name="files" multiple
                               :data="token"
                               :show-file-list="false"
                               v-loading="shareFileLoading"
                               :on-success="handleUploadShareImageUrlSuccess"
                               :before-upload="beforeShareImageUrlUpload">

                      <img v-if="form.shareImageUrl" :src="form.shareImageUrl" style="width: 150px;height: 150px">

                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                  <div class="tips mar-t-3">建议尺寸：750*750像素</div>
                </el-form-item>

                <el-form-item label="商品分类：" label-width="170px" prop="goodscategoryIds">
                    <el-cascader v-model="form.goodscategoryIds"
                                 :props="{ checkStrictly: true }" change-on-select
                            placeholder="选择商品分类"
                            :options="categoryData"
                            class="default-input"
                            filterable></el-cascader>
                </el-form-item>

                <el-form-item label="商品标签：" label-width="170px">
                    <el-checkbox-group v-model="form.labelTypes">
                        <template v-for="(val,key) in dict.labelType">
                            <el-checkbox  :index="key" :label="key">{{val}}</el-checkbox>
                        </template>
                    </el-checkbox-group>
                </el-form-item>

            </el-form-item>
        </el-form>
    </div>
</template>


<script>
  import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
  import { listGoodsCategory } from '@/api/goods/goods'
  import { getDictCommon } from '@/api/common/common.js'
  import { getToken } from '@/utils/auth'
  import draggable from 'vuedraggable'

  export default {
    components: {
      draggable
    },
    directives: {
      // 拖动窗口
      elDragDialog
    },
    props: ['dict'],
    data() {
      return {
        curIndex: -1,
        curHover: -1,
        token: '',
        form: {
          sortNo: 0,
          title: '', // 标题
          unit: '', // 单位
          goodsType: '30', // 商品类型 30: 实物商品, 2: 批发商品
          goodsImages: [],
          labelTypes: [], // 1: 推荐, 2: 热门,3: 新品4: 包邮
          shareImageUrl: '',
          goodscategoryIds: [] // // 商品分类
        },
        comDict: {},
        enterpriseId: this.getEnterpriseId(),
        fileLoading: false,
        shareFileLoading: false,
        // 商品的所有分类json
        categoryData: [],
        checked: {},
        rules: {
          sortNo: [
            { pattern: /^[0-9]*[0-9][0-9]*$/, message: '请填写正确排序' }
          ],
          title: [
            { max: 100, message: '排序长度最多输入 100 个字符' },
            { required: true, message: '请填写商品名称', trigger: 'blur' }
          ],
          goodscategoryIds: [
            { required: true, message: '请填写商品分类', trigger: 'blur' }
          ]
        }
      }
    },
    // 初始化页面
    created() {
      this.token = { accessToken: getToken() }
      this.listGoodsCategory()
      this.initGoodsEdit()
      this.initDictCommon()
    },
    methods: {
      initGoodsEdit() {
        const that = this
        this.$bus.$on('goods.edit.data', function(data) {
          that.form.sortNo = that.$utils.isExist(data.sortNo) ? data.sortNo : '0'
          that.form.title = that.$utils.isExist(data.title) ? data.title : ''
          that.form.unit = that.$utils.isExist(data.unit) ? data.unit : ''
          that.form.goodsType = that.$utils.isExist(data.goodsType) ? data.goodsType + '' : '1'
          that.form.shareImageUrl = that.$utils.isExist(data.shareImageUrl) ? data.shareImageUrl + '' : ''
          that.form.goodsImages = that.$utils.isExist(data.goodsImages) ? data.goodsImages : ''
          that.form.labelTypes = that.$utils.isExist(data.labelTypes) ? data.labelTypes : []
          const oneCategoryId = that.$utils.isExist(data.oneCategoryId) ? data.oneCategoryId : ''
          const twoCategoryId = that.$utils.isExist(data.twoCategoryId) ? data.twoCategoryId : ''
          const threeCategoryId = that.$utils.isExist(data.threeCategoryId) ? data.threeCategoryId : ''
          var arr = [] // 创建一个空数组
          if (that.$utils.isExist(oneCategoryId) && that.$utils.isExist(twoCategoryId) && that.$utils.isExist(threeCategoryId)) {
            arr.push(oneCategoryId)
            arr.push(twoCategoryId)
            arr.push(threeCategoryId)
            that.form.goodscategoryIds = arr
          }
        })
      },
      initDictCommon() {
        getDictCommon().then(response => {
          this.comDict = response.data
        })
      },
      // 展示3级任务类型
      showSubCategory(key) {
        this.picData[key].show = true
        const changeData = this.picData[key].show
        this.$delete(this.picData[key], 'show')
        this.$set(this.picData[key], 'show', changeData)
      },
      // 隐藏3级任务类型
      hideSubCategory(key) {
        this.picData[key].show = false
      },
      goodsMouseEnter(key) {
        this.form.goodsImages[key].show = true
        const changeData = this.form.goodsImages[key].show
        this.$delete(this.form.goodsImages[key], 'show')
        this.$set(this.form.goodsImages[key], 'show', changeData)
      },
      goodsMouseLeave(key) {
        this.form.goodsImages[key].show = false
      },
      // 删除图片
      deleteImgages(item, key) {
        const goodsImages = this.form.goodsImages
        goodsImages.splice(key, 1)
        this.form.goodsImages = goodsImages
        this.setMainImageFlag()
      },
      // 修改图片
      changeImgages(item, key) {
        const goodsImages = this.form.goodsImages
        const arry = this.swapArray(goodsImages, key, 0)
        this.form.goodsImages = arry
        this.setMainImageFlag()
      },
      // 设置主图
      setMainImageFlag() {
        const goodsImages = this.form.goodsImages
        goodsImages.forEach((item, index) => {
          if (index === 0) {
            item.mainImageFlag = 1
          } else {
            item.mainImageFlag = 0
          }
        })
        this.form.goodsImages = goodsImages
      },
      swapArray(arr, index1, index2) {
        arr[index1] = arr.splice(index2, 1, arr[index1])[0]
        return arr
      },
      // 获取类目
      listGoodsCategory() {
        listGoodsCategory(this.enterpriseId).then(response => {
          this.categoryData = response.data
        })
      },
      checkForm() {
        const goodscategoryIds = this.form.goodscategoryIds
        // 需要校验的集合
        const checkArrays = []
        checkArrays.push('sortNo')
        checkArrays.push('title')
        checkArrays.push('goodscategoryIds')
        let ret = true
        this.$refs.form.validateField(checkArrays, (valid) => {
          if (valid !== '') {
            this.$message.error(valid)
            ret = false
            return
          }
        })

        if (!ret) {
          return false
        }

        if (goodscategoryIds.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择商品类目!'
          })
          return false
        }
        return true
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        this.fileLoading = true
        return (isJPG || isBMP || isGIF || isPNG)
      },
      handleUploadSuccess(res, file) {
        if (this.form.goodsImages.length > 5) {
          this.$message({
            type: 'error',
            message: '最多只能上传5张主图'
          })
          return false
        }
        this.fileLoading = false
        if (res.code === 101) {
          const imageUrl = res.data[0]
          const goodsImages = this.form.goodsImages
          var obj = {
            imageUrl: imageUrl,
            mainImageFlag: 0
          }
          goodsImages.push(obj)
          this.form.goodsImages = goodsImages
          this.setMainImageFlag()
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      },
      beforeShareImageUrlUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        this.shareFileLoading = true
        return (isJPG || isBMP || isGIF || isPNG)
      },
      handleUploadShareImageUrlSuccess(res, file) {
        this.shareFileLoading = false
        if (res.code === 101) {
          const imageUrl = res.data[0]
          this.form.shareImageUrl = imageUrl
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      },
      getdata(evt) {
        // 这里evt.draggedContext后续的内容根据具体的定义变量而定
      },
      datadragEnd(evt) {
        evt.preventDefault()
        const filters = this.form.goodsImages
        for (let a = 0; a < filters.length; a++) {
          filters[a].index = a
        }
        this.form.goodsImages = filters
      },
      itemOver(index) {
        this.curHover = index
      },
      itemOut(index) {
        this.curHover = index
      }
    }
  }
</script>

<style lang="less" scoped>
  .noraml-hide{
    display: none!important;
  }
  .active{
    display: block!important;
  }
  .span-bar{
    padding: 0 50px;
  }
  .remove-btn{
    padding: 7px 6px!important;
  }
  .long-input{
    width: 80%;
  }
  .long-input-2{
    min-width: 55%;
    margin-right: 10px;
  }
  .long-input-3{
    width: 55%;
  }
  .short-input{
    width: 20%;
  }
  .short-input-2{
    width: 25%;
  }
  .default-input{
    width: 50%;
  }
  .tips{
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }
  .picture{
    width: 148px;
    height: 148px;
    display: block;
  }
  .pic-bar{
    position: relative;
    display: inline-block;
    .close-icon{
      position: absolute;
      right: -30px;
      top: -11px;
      width: 31px;
      height: 40px;
      padding: 0 7px;
      cursor: pointer;
    }
    span{
      position: absolute;
      right: 0;
      bottom: 0;
      width: 100%;
      display: block;
      color: #fff;
      text-align: center;
      padding: 3px 0;
      background: rgba(0,0,0,0.5);
      cursor: pointer;
    }
  }
  .pic-add{
    background: #fff;
    border: #d3d3d3 1px dashed;
    border-radius: 5px;
    padding: 0 45px;
  }
</style>
